--[[
FilePath: \Lua\View\UISealCrystal\UISealCrystal.lua
封印水晶活动
--]]

require 'View/UIBase/UIBase'

UISealCrystal = UIBase.New(PanelNames.UISealCrystal)
local _M = UISealCrystal

_M.hasInit = false
_M.ContentItems = {}
_M.maskItemContents = nil;
_M.isAct = false
_M.isPlayEffect = false

function _M.Init(func, id, goFunc)
    _M.activeId = id
    _M.goFunc = goFunc
    UIBase.Init(_M, func)
end

function _M:OnCreate()
    if not _M.hasInit then
        self:RegisterOnClick(self:GetChild("Backbtn"), self.OnClose)
        self.btnHelp = self:GetChild("help")
        self.CashLb = self:GetChild("CashLb");
        self.cashJump = self.CashLb:GetChild("btnJump");
        self.CoinLb = self:GetChild("CoinLb");
        local group = self:GetChild("group");
        self.icon = group:GetChild("Bg");
        self.maskList = group:GetChild("CoverList");
        self.btnAct = self:GetChild("Button");
        self.costIcon = self.btnAct:GetChild("item");
        self.costNum = self.btnAct:GetChild("text");
        self.costNum2 = self.btnAct:GetChild("text2");
        self.crystalList = self:GetChild("CrystalList");
        self.btnGift = self:GetChild("gift");
        self.giftController = self.btnGift:GetController("status");
        _M.hasInit = true

        self.crystalList.itemRenderer = self.RefreshItem;

        self:addEvent()
    end
end

function _M:addEvent()
    self:RegisterEvent(Config.EventType.Fresh_Active,self.Refresh);
    self.btnAct.onClick:Add(self.onClickAct, self)
    self.btnGift.onClick:Add(self.onClickGift, self)
    self.btnHelp.onClick:Add(self.HelpTip, self)
    self.cashJump.onClick:Add(self.onClickCashJump, self);
end

function _M:removeEvent()
    self.btnAct.onClick:Remove(self.onClickAct)
    self.btnGift.onClick:Remove(self.onClickGift)
    self.btnHelp.onClick:Remove(self.HelpTip)
    self.cashJump.onClick:Remove(self.onClickCashJump);
end

function _M:onClickCashJump()
    if self.tableData ~= nil then
        showUI(PanelNames.UICommonSource, function()
            self:OnClose();
            if self.goFunc then
                self.goFunc();
            end
        end, { self.tableData.f_CostItemId }, self.cashJump.parent);
    end
end

function _M:HelpTip()
    if self.isPlayEffect then
        return;
    end

    if self.tableData ~= nil and self.tableData.f_ExplainTitle ~= nil and self.tableData.f_ExplainText ~= nil then
        logicMgr.UIShowManager.ShowCommonTips(tostring(self.tableData.f_ExplainTitle), tostring(self.tableData.f_ExplainText));
    end
end

function _M:OnClose()
    if self.isPlayEffect then
        return;
    end
    self:OnBack();
    logicMgr.HeroManager.setGetNewHeroShow();
end

function _M:onClickAct()
    if self.isAct then
        return;
    end
    if self.isPlayEffect then
        return;
    end
    if self.serverData.crystalNum == -1 then
        UISysTips.AddMsg(getLanguage("ActivityDesc1100101"));
        return;
    end
    if self.serverData.crystalNum < 1 then
        UISysTips.AddMsg(getLanguage("ActivityDesc1100102"));
        return;
    end
    if not self.hasEnoughNum then
        UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"),getLanguage(self.costItemName)));
        return;
    end
    self.isAct = true;
    ActivityHandler.sendReqLightCrystalMessage({_M.activeId});
end

function _M:onClickGift()
    if self.isPlayEffect then
        return;
    end

    local rewardId = tonumber(self.serverData.rewardId);
    if rewardId > 0 then
        ActivityHandler.sendReqActivityDrawRewardMessage({_M.activeId, rewardId});
    else
        --显示
        showUI(PanelNames.UISealCrystalTips, nil, self.activeId, self.serverData.serverRewards, self.serverData.puzzleNum);
    end
end

-- 显示
function _M:OnEnable()
    self:Refresh();
    logicMgr.HeroManager.setGetNewHeroShow(true);
end

function _M:Refresh()
    if self.activeId == nil or not _M.hasInit then
        self:OnBack();
    else
        self.tableData, self.serverData = logicMgr.ActiveManager.getActiveData(self.activeId);
        if self.serverData == nil then
            self:OnBack();
            return;
        end
    end
    if self.isAct then
        self.isAct = false;
        self.crystalList.numItems = tonumber(self.tableData.f_CrystalNum);
    end
    if self.maskItemContents == nil then
        local heroIcon = self.tableData.f_HeroIcon;
        if heroIcon ~= nil and heroIcon ~= "" then
            self.icon.url =heroIcon;
        end
        local sealNum = tonumber(self.tableData.f_SealNum);
        self.maskItemContents = {};
        for i = 1, sealNum do
            local item = self.maskList:AddItemFromPool()
            table.insert(self.maskItemContents, item);
        end
        self.crystalList.numItems = tonumber(self.tableData.f_CrystalNum);
        self:refreshPuzzle();
    end
    --[[
    local costItemId = self.tableData.f_CostItemId;
    local haveNum = logicMgr.ItemManager.getBagNumByTableID(costItemId);
    self.hasEnoughNum = false;
    self.costItemName = G.dataTable["t_item"][tostring(costItemId)].f_ItemName;
    if haveNum >= 1 then
        self.hasEnoughNum = true;
        self.costNum.text = "[color=#A0C776]"..haveNum.."[/color]/";
    else
        self.costNum.text = "[color=#FF2A4D]"..haveNum.."[/color]/";
    end
    --]]
    local itemCfg = G.dataTable["t_item"];
    self.CoinLb.icon = EnumConst.AtlasPath.ItemAtlas .. itemCfg["1"].f_Icon;
    local haveNum = logicMgr.ItemManager.getBagNumByTableID(1);
    self.CoinLb.title = haveNum;

    local costItemId = self.tableData.f_CostItemId;
    self.costItemName = itemCfg[tostring(costItemId)].f_ItemName;
    local costIcon = itemCfg[tostring(costItemId)].f_Icon;
    self.CashLb.icon = EnumConst.AtlasPath.ItemAtlas .. costIcon;
    self.costIcon.icon = EnumConst.AtlasPath.ItemAtlas .. costIcon;
    haveNum = logicMgr.ItemManager.getBagNumByTableID(costItemId);
    self.CashLb.title = getNumString(haveNum);
    self.hasEnoughNum = false;
    if haveNum >= 1 then
        self.hasEnoughNum = true;
        self.costNum.color = Color.New(211/255, 217/255, 221/255, 1)
        self.costNum2.color = Color.New(211/255, 217/255, 221/255, 1)
    else
        self.costNum.color = Color.New(1, 42/255, 77/255, 1)
        self.costNum2.color = Color.New(1, 42/255, 77/255, 1)
    end

    local rewardId = tonumber(self.serverData.rewardId);
    if rewardId == -1 then
        self.giftController.selectedIndex = 2;
    elseif rewardId > 0 then
        self.giftController.selectedIndex = 1;
    else
        self.giftController.selectedIndex = 0;
    end
end

function _M.GetCrystalReward(activityId, index, puzzleId, items)
    if activityId == _M.activeId then
        _M:refreshPuzzle(items, index, puzzleId);
    end
end

function _M:refreshPuzzle(items, index, puzzleId)
    if self.maskItemContents == nil or self.serverData.status == nil then
        return;
    end
    if items == nil then
        local puzzleStatus = self.serverData.status;
        for i = 1, #self.maskItemContents do
            if puzzleStatus[i] ~= nil then
                self.maskItemContents[i]:GetChild("n0").alpha = 0;
            end
        end
    else
        --播放动效
        self.isPlayEffect = true;
        local idleAniTime = 1;
        if self.ContentItems[index - 1] ~= nil then
            idleAniTime = self.ContentItems[index - 1]:PlayEffect();
        end
        _M.timerId = utimer.timeCall(function()
            utimer.remove(_M.timerId);
            _M.timerId = nil;
            logicMgr.HeroManager.showNewHero(function ()
                if items ~= nil then
                    local rewards = {};
                    for k,v in pairs(items) do
                        local itemData = logicMgr.CostManager.getItemOrEquipDataByIdAndNum(v.itemModelId, v.num);
                        if itemData ~= nil then
                            table.insert(rewards, itemData);
                        end
                    end
                    if #rewards > 0 then
                        showUI(PanelNames.UICommonItemGet, nil, nil, 3, rewards, function()
                            _M.maskItemContents[puzzleId]:GetChild("n0").alpha = 0;
                        end);
                    end
                end
            end);
            _M.isPlayEffect = false;
            _M.crystalList.numItems = tonumber(_M.tableData.f_CrystalNum);
        end, idleAniTime * 600, 1);
    end
end

function _M.RefreshItem(index, itemObj)
    _M:CreateItem(index, itemObj)
    if _M.serverData.crystaTime == nil then
        _M.ContentItems[index]:OnShow(0, index + 1)
    else
        local serverTime = _M.serverData.crystaTime[tostring(index + 1)];
        if serverTime == nil then
            _M.ContentItems[index]:OnShow(0, index + 1)
        else
            _M.ContentItems[index]:OnShow(tonumber(serverTime), index + 1)
        end
    end
end

function _M:CreateItem(index,itemObj)
    if self.ContentItems[index] then
        return
    end
    local item = self.UISealCrystalItem.New()
    self.ContentItems[index] = item
    item:OnCreate(itemObj,self)
end

-- 隐藏
function _M:OnDisable()

end

-- 卸载
function _M:OnDestroy()
    self:removeEvent();

    if self.ContentItems then
        for key, value in pairs(self.ContentItems) do
            value:OnDestroy()
        end
        self.ContentItems = {}
    end
    self.maskItemContents = nil;
    if self.timerId ~= nil then
        utimer.remove(self.timerId)
        self.timerId = nil;
    end
    self.isAct = false;
end

-- item类
_M.UISealCrystalItem = Class("UISealCrystalItem",UIComponentInterface)
local _M_T = _M.UISealCrystalItem
function _M_T:OnCreate(obj,parent)
    self.parent = parent
    self.fguiObj = obj
    self.timer = nil;

    self.text = self.fguiObj:GetChild("text")
    self.status = self.fguiObj:GetController("Type")
    self.effect = self.fguiObj:GetChild("effect_sjlq")
    self.isGet = false
    self.hasReward = false
    self.parent:RegisterOnClick(self.fguiObj,self.getReward,self)
end

function _M_T:OnShow(rewardTime, index)
    self.rewardTime = rewardTime;
    self.index = index;
    self:Refresh()
end

function _M_T:PlayEffect()
    if self.effect == nil then
        return 0;
    end
    self.status.selectedIndex = 3;
    local idleAniTime = self.effect.spineAnimation.state.Data.SkeletonData:FindAnimation("idle1").Duration;
    self.effect.spineAnimation.state:SetAnimation(0, "idle1", false);
    return idleAniTime;
end

function _M_T:Refresh()
    self.isGet = false;
    self.hasReward = false;
    if self.timer ~= nil then
        self:RemoveTimeCall(self.updateActiveCountDown)
        self.timer = nil;
    end
    if self.rewardTime == 0 then
        self.text.text = getLanguage("ActivityDesc1100103")
        self.status.selectedIndex = 0;
    else
        local serverTime = HelperFunc.GetServerTime();
        local time = self.rewardTime;
        if serverTime >= time then
            self.text.text = getLanguage("ActivityDesc1100104")
            self.hasReward = true
            self.status.selectedIndex = 2
        else
            self.endCountDown = time - serverTime;
            self.status.selectedIndex = 1
            self:updateActiveCountDown()
            self.timer = self:TimeCall(self.updateActiveCountDown, 1000, -1)
        end
    end
end

function _M_T:updateActiveCountDown()
    if self.endCountDown == nil then
        return;
    end
    if self.endCountDown <= 0 then
        self.text.text = getLanguage("ActivityDesc1100104")
        self.hasReward = true
        self.status.selectedIndex = 2
        self:RemoveTimeCall(self.updateActiveCountDown)
        self.timer = nil
    else
        self.text.text = HelperFunc.GetTimeStr2(self.endCountDown);
    end
    self.endCountDown = self.endCountDown - 1;
end

function _M_T:getReward()
    if self.isGet or not self.hasReward or self.parent.isPlayEffect then
        return;
    end
    self.isGet = true;
    ActivityHandler.sendReqCrystalRewardMessage(_M.activeId, self.index);
end

function _M_T:OnDestroy()
    if self.timer ~= nil then
        self:RemoveTimeCall(self.updateActiveCountDown)
        self.timer = nil;
    end
end

return _M;